package com.chezhujie.www.controller;

import com.chezhujie.www.core.StaticMap;
import com.chezhujie.www.domain.vo.WeixinInfo;
import com.chezhujie.www.service.WeixininfoService;
import com.xy.user.base.controller.BaseController;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/5/11.
 */
//@Controller
public class HtmlController extends BaseController {

    @Autowired
    private WeixininfoService weixininfoService;

//    @RequestMapping({"/wxhtml/*.html","/index.html"})
    public String getInfo1(HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) throws Exception {
        return commonhtml(req,resp, model);
    }


    public String commonhtml(HttpServletRequest req, HttpServletResponse resp, ModelMap model) throws Exception {
        String code = req.getParameter("code");//0微信访问1直接访问

        String strDirPath = req.getSession().getServletContext().getRealPath("/");

        if(StringUtils.isNotBlank(code)){
            try {
                WeixinInfo weixin = weixininfoService.getWeixinInfo(code, StaticMap.appid, StaticMap.secret);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("微信更新code值失败："+e.getMessage(),e);
                String url = getParameterUrl(req);
                model.addAttribute("url", url);
                model.addAttribute("appid", StaticMap.appid);
                return "weixinLogin";
            }

            String uri = getURI(req);
            File file = new File(strDirPath+uri);
            System.out.println("file:"+strDirPath+uri);
            if(file==null){
                throw new FileNotFoundException("文件没有找到！文件路径："+uri);
            }
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().print(FileUtils.readFileToString(file));
//            write.flush();
            resp.getWriter().close();
            return null;

        }else{
            String url = getParameterUrl(req);

            System.out.println(url);
            url=getURLEncoderString(url);
//            String uri ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ StaticMap.appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
//            System.out.println(uri);
            model.addAttribute("url", url);
            model.addAttribute("appid", StaticMap.appid);
//            model.addAttribute("appid","wx5e3453d525417756");
//            resp.sendRedirect(uri);
            return "weixinLogin";
        }

    }

    /**
     * 跳转微信授权页面
     * @param returnUrl
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping("getWeixinAuth.do")
    public String getWeixinAuth(@RequestParam(required = true) String returnUrl , HttpServletRequest req, HttpServletResponse resp,
                                ModelMap model){
            String url = returnUrl;
            url=getURLEncoderString(url);
            model.addAttribute("url", url);
            model.addAttribute("appid", StaticMap.appid);
            return "weixinLogin";

    }

    private String getParameterUrl(HttpServletRequest req) {
        String url  = req.getRequestURL().toString();
        Map<String, String> map = getRequestMap(req);
        String str="";
        if(map.size()!=0){
            str+="?";
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            str+=entry.getKey()+"="+entry.getValue()+"&";
        }
        if(str.contains("&")){
            url+=str.substring(0,str.lastIndexOf("&"));
        }
        return url;
    }

    private static Map<String,String> getRequestMap(HttpServletRequest req){
        Map<String, String> requestMap = new HashMap<String,String>();
        Enumeration<String> str = req.getParameterNames();
        String string = null;
        while(str.hasMoreElements()&&(string = str.nextElement())!=null){
            requestMap.put(string, req.getParameter(string));
        }
        return requestMap;
    }
    /**
     * 获得第三个路径分隔符的位置
     *
     * @param request
     * @throws IllegalStateException
     *             访问路径错误，没有三(四)个'/'
     */
    private static String getURI(HttpServletRequest request)
            throws IllegalStateException {

        UrlPathHelper helper = new UrlPathHelper();
        String uri = helper.getOriginatingRequestUri(request);
        String ctxPath = helper.getOriginatingContextPath(request);
        return uri.replace(ctxPath,"");

    }
    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
